package com.atguigu.yygh.user.service.impl;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.helper.JwtHelper;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author study
 * @version 1.0
 * @date 2021/5/8 10:54
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Override
    public Map<String, Object> loginUser(LoginVo loginVo) {
        //得到注册的手机号码
        final String phone = loginVo.getPhone();
        final String code = loginVo.getCode();
        if (StringUtils.isAnyBlank(phone, code)) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        //TODO 判断验证码
        QueryWrapper<UserInfo> query = new QueryWrapper<>();
        query.eq("phone", phone);
        UserInfo userInfo = baseMapper.selectOne(query);
        if (Objects.isNull(userInfo)) {
            //添加信息到数据库
            userInfo = new UserInfo();
            userInfo.setName("");
            userInfo.setPhone(phone);
            //1 表示正常，0表示锁定
            userInfo.setStatus(1);
            this.save(userInfo);
        }
        //校验是否被禁用
        if (userInfo.getStatus() == 0) {
            throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        //TODO 记录登录
        //返回页面显示名称
        HashMap<String, Object> map = new HashMap<>(2);
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        //TODO token的生成
        map.put("token", JwtHelper.createToken(userInfo.getId(), name));
        return map;
    }
}
